package com.tbvtc.agriculturalcreditchainserver2025.ws;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.tbvtc.agriculturalcreditchainserver2025.entity.FarmlandInfo;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.Iot.huaWei.HuaWeiIotAllLandRespond;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.Iot.huaWei.HuaWeiIotRespond;
import com.tbvtc.agriculturalcreditchainserver2025.service.ICropService;
import com.tbvtc.agriculturalcreditchainserver2025.service.IFarmlandInfoService;
import com.tbvtc.agriculturalcreditchainserver2025.service.IpfsService;
import com.tbvtc.agriculturalcreditchainserver2025.service.PestService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.BlockBaseUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.BlockchainUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.ImageReceiverUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestHttpUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestReportUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestUtils;


import com.tbvtc.agriculturalcreditchainserver2025.utils.UserType;
import com.tbvtc.agriculturalcreditchainserver2025.utils.huawei.HwCloudIot;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.utils.weather.WeatherData;
import com.tbvtc.agriculturalcreditchainserver2025.utils.weather.WeatherResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WebSocketTask {
    @Autowired
    private IotWebSocketServer webSocketServer;

    /**
     * 通过WebSocket每隔10秒向客户端发送消息
     */
    @Autowired
    private ObjectMapper objectMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private BlockchainUtils blockchainUtil;
    @Resource
    private BlockBaseUtils blockBaseUtils;
    @Resource
    private HwCloudIot hwCloudIot;
    @Resource
    private IFarmlandInfoService farmlandInfoService;
    @Resource
    private RestTemplate restTemplate;




//    @Scheduled(cron = "0/30  * * * * ?")
//    public void sendMessageToClient() {
//        try {
//            List<HuaWeiIotRespond> respond = new ArrayList<>();
//            Map<String, Double> temAndHumInfo = hwCloudIot.getTemAndHumInfo();
//            temAndHumInfo.entrySet().forEach(stringDoubleEntry -> {
//                HuaWeiIotRespond temRespond = new HuaWeiIotRespond(stringDoubleEntry.getKey(),
//                        stringDoubleEntry.getValue().toString(), LocalDateTime.now().toString());
//                respond.add(temRespond);
//            });
//            int value = hwCloudIot.getIlluminationValue();
//            HuaWeiIotRespond gzValue = new HuaWeiIotRespond("light", String.valueOf(value), LocalDateTime.now().toString());
//            respond.add(gzValue);
//            double soilMoistureInfo = hwCloudIot.getSoilMoistureInfo();
//            HuaWeiIotRespond SoilMoisture = new HuaWeiIotRespond("SoilMoisture", String.valueOf(soilMoistureInfo), LocalDateTime.now().toString());
//            respond.add(SoilMoisture);
//            String json = objectMapper.writeValueAsString(respond);
//            webSocketServer.sendToAllClient(json);// HH:mm:ss 表示24小时制
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }


    @Scheduled(fixedDelay = 1000 * 60 * 60)
    public void compareBlockHeights() {
        try {
            BigInteger newBlockNumber = blockchainUtil.getBlockNumber(blockBaseUtils.getPemFilePath(UserType.ADMIN));
            String oldBlockNumber = stringRedisTemplate.opsForValue().get(RedisConstant.BLOCK_NUMBER_KEY);
            if (oldBlockNumber == null) {
                stringRedisTemplate.opsForValue().set(RedisConstant.BLOCK_NUMBER_KEY, newBlockNumber.toString(), RedisConstant.BLOCK_NUMBER_TIME, TimeUnit.MINUTES);
            }
            if (!newBlockNumber.toString().equals(oldBlockNumber)) {
                stringRedisTemplate.opsForValue().set(RedisConstant.BLOCK_NUMBER_KEY, newBlockNumber.toString(), RedisConstant.BLOCK_NUMBER_TIME, TimeUnit.MINUTES);
                stringRedisTemplate.delete(RedisConstant.BLOCK_TR_KEY);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
//    @Scheduled(cron = "0/30  * * * * ?")
//    public void sendAllMessageToClient() throws Exception {
//        List<Integer> ids = farmlandInfoService.listObjs(new LambdaQueryWrapper<FarmlandInfo>()
//                        .select(FarmlandInfo::getId),
//                obj -> (Integer) obj
//        );
//        List<HuaWeiIotAllLandRespond> huaWeiIotAllLandRespondList=new ArrayList<>();
//        for (Integer id : ids) {
//            HuaWeiIotAllLandRespond huaWeiIotAllLandRespond=new HuaWeiIotAllLandRespond();
//            huaWeiIotAllLandRespond.setId(id);
//            huaWeiIotAllLandRespond.setWeather(getWeather());
//            huaWeiIotAllLandRespond.setHuaWeiIotRespondList(getIotValue());
//            huaWeiIotAllLandRespondList.add(huaWeiIotAllLandRespond);
//        }
//        String json = objectMapper.writeValueAsString(huaWeiIotAllLandRespondList);
//        System.out.println(json);
//        webSocketServer.sendToAllClient(json);// HH:mm:ss 表示24小时制
//
//    }
    public List<HuaWeiIotRespond> getIotValue() throws Exception {
        List<HuaWeiIotRespond> respond = new ArrayList<>();
        Random random = new Random();
        LocalDateTime now = LocalDateTime.now(); // 统一时间戳，避免循环内多次生成
        String recordTime = now.toString();


        // 处理温湿度数据
        Map<String, Double> temAndHumInfo = hwCloudIot.getTemAndHumInfo();
        temAndHumInfo.entrySet().forEach(entry -> {
            // 生成-2到2之间的随机浮动值
            double fluctuation = random.nextDouble() * 4 - 2;
            // 计算浮动后的值
            double originalValue = entry.getValue();
            double fluctuatedValue = originalValue + fluctuation;
            // 创建新的响应对象（修复原代码中对象复用导致的覆盖问题）
            HuaWeiIotRespond temRespond = new HuaWeiIotRespond();
            temRespond.setName(entry.getKey());
            temRespond.setValue(String.valueOf(fluctuatedValue));
            temRespond.setRecordTime(recordTime);
            respond.add(temRespond);
        });

        // 处理光照值
        int illuminationValue = hwCloudIot.getIlluminationValue();
        int illuminationFluctuation = random.nextInt(5) - 2; // -2到2的整数波动
        int fluctuatedIllumination = illuminationValue + illuminationFluctuation;
        HuaWeiIotRespond gzValue = new HuaWeiIotRespond(
                "light",
                String.valueOf(fluctuatedIllumination),
                recordTime
        );
        respond.add(gzValue);

        // 处理土壤湿度
        double soilMoistureInfo = hwCloudIot.getSoilMoistureInfo();
        double soilFluctuation = random.nextDouble() * 4 - 2;
        double fluctuatedSoil = soilMoistureInfo + soilFluctuation;
        HuaWeiIotRespond soilMoisture = new HuaWeiIotRespond(
                "SoilMoisture",
                String.valueOf(fluctuatedSoil),
                recordTime
        );
        respond.add(soilMoisture);

        return respond;
    }

    public String getWeather(){
        String weather = stringRedisTemplate.opsForValue().get(RedisConstant.WEATHER_KEY);
        if (weather == null){
            String id = "10009227";
            String key="58b23d9bbeb18de07a2cc27fea19e0a1";
            String lon = "116.307878";
            String lat = "40.057027";     // 纬度（示例：北京）

            String url = String.format(
                    "https://cn.apihz.cn/api/tianqi/tqybjw5.php?id=%s&key=%s&lat=%s&lon=%s",
                    id, key, lat, lon
            );
            WeatherResponse forObject = restTemplate.getForObject(url, WeatherResponse.class);
            List<WeatherData> data = forObject.getData();
            stringRedisTemplate.opsForValue().set(RedisConstant.WEATHER_KEY,data.get(0).getWeather(),RedisConstant.WEATHER_TIME,TimeUnit.MINUTES);
            return data.get(0).getWeather();
        }
       return weather;
    }


}
